<?php
class user {
	var $logged=false;
	var $id;
	var $vals=array();
  public function user($id=false){
  	global $core,$config;
  	if(!session_id()){
		session_start();	
		}
    $this->id=$id;
    if(!$this->id&&$_SESSION['user_id']){
      $this->id=$_SESSION['user_id'];
      $this->logged=true;
    }
	if(array_key_exists("signed_request", $_POST)&&$this->id==$_SESSION['user_id']){
		$facebook=&$core->getApp("facebook");
		$facedata=$facebook->parse_signed_request($_POST["signed_request"],$config->defaults["facebook"]->app_secret);
		if($this->get("fb_id")==$_POST["user_id"]){
			$this->set("fb_token",$_POST["token"]);
			$this->set("fb_expire",$_POST["expires"]);
		}
		else {
			$this->loginFacebook($facedata);
		}
	}
  }
  public function get($param){
    global $core,$config;
    $db=&$core->getDB();
    $con=&$db->getConexion();
	if($param=="URL"){
		return $this->getLink();
	}
	if(!array_key_exists($param, $this->vals)){
	    $q="select `u`.`".mysql_real_escape_string($param)."` as 'param'"
	    	.($param=="fb_token"?",`u`.`fb_expire` as 'fb_exire'":"")
	      ."from `usuarios` as `u`
	      where `u`.`id_cliente`='".mysql_real_escape_string($this->id)."'
	      limit 1";
	    $r=mysql_query($q);
	    if($r&&mysql_num_rows($r)){
	      $i=mysql_fetch_array($r,MYSQL_ASSOC);
			//if($param=="fb_token"&&$i["fb_exire"]<=time()){
				
  				//unset($_SESSION['user_id']);
				//$facebook=&$core->getApp("facebook");
				//$url=$facebook->getAuthURL($config->defaults["facebook"]->app_id,$config->defaults["facebook"]->appURL,$config->defaults["facebook"]->scope);
				//header("location:".$url);
				//exit;
			//}
	      $this->vals[$param]= $i["param"];
	    }
	}
	return $this->vals[$param];
  }
  public function moveAvatar($path){
  	global $config;
	if(strpos($path,"http")===false){
		$imgpath=$config->paths["base"].$path;	
      	$info=getimagesize($imgpath);
      switch($info["mime"]){
		case "image/jpeg":
		  $img=imagecreatefromjpeg($imgpath);
		  break;
		case "image/jpg":
		  $img=imagecreatefromjpeg($imgpath);
		  break;
		case "image/gif":
		  $img=imagecreatefromgif($imgpath);
		  break;
		case "image/png":
		  $img=imagecreatefrompng($imgpath);
		  break;
	      }
      if($img){
		$img2 = imagecreatetruecolor(140, 140);
		imagecopyresampled($img2,$img,0,0,0,0,140,140,intval($info[0]),intval($info[1]));
		$path=tempnam($config->paths["avatars"], "Avatar_");
		$path.=".jpg";
		imagejpeg( $img2,$path,100);
		imagedestroy($img);
		imagedestroy($img2);
		return str_replace($config->paths["base"],"",$path);
	      }
	  else {
	  	return 'galeria/perfil/avatar.gif';
	  }
	}
	else {
		return $path;
	}
  }
  public function set($param, $value){
    global $core;
	if($param=="avatar"){
		$value=$this->moveAvatar($value);
	}
    $db=&$core->getDB();
    $con=&$db->getConexion();
    $q="update `usuarios` as `u`
	set `u`.`".mysql_real_escape_string($param)."`='".mysql_real_escape_string($value)."'
	where `u`.`id_cliente`='".mysql_real_escape_string($this->id)."'
	limit 1";
    $r=mysql_query($q);
	$this->vals[$param]=$value;
  }
  public function  getFB_login_link(){
    global $config;
    $url="http://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URI&state=SOME_ARBITRARY_BUT_UNIQUE_STRING&scope=email";
    $p=array(
      "YOUR_APP_ID"=>$config->defaults["facebook"]->app_id,
      "YOUR_REDIRECT_URI"=>"http://www.e-spacios.com/app/facebook/log",
      "SOME_ARBITRARY_BUT_UNIQUE_STRING"=>md5($this->get("username"))
     );
    $url=str_replace(array_keys($p),$p,$url);
	$urlactual="http".($_SERVER["HTTPS"]?"s":"")."://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
	setcookie("actualURL",$urlactual,0,"/");
    return $url;
  }
  public function forceLogin(){
  	$q="select `id_cliente`
	      from `usuarios`
	      where `id_cliente`='".mysql_real_escape_string($this->id)."'
	      limit 1";
	$r=mysql_query($q);
	if(mysql_num_rows($r)){
	    $i=mysql_fetch_array($r,MYSQL_ASSOC);
		$_SESSION['user_id'] = $i["id_cliente"];
	    $this->logged=true;
	    $this->id=$i["id_cliente"];
	}
  }
  public function facebookLogged(){
    $logged=false;
    $token=$this->get("fb_token");
    if($token){
      $expire=$this->get("fb_expire");
      if($expire>time()){
	  $logged=true;
      }
    }
    return $logged;
  }
  public function logout(){
  	global $core;
   unset($_SESSION['user_id']);
	  //$actividades=$core->getApp("actividades");
	  //$actividades->report($this,'$$has_logout$$',$this->getLink());
    header("location:/");
    exit;
  }
  public function getAvatar(){
  	$avatar=$this->get("avatar");
	if(!$avatar){
		if(file_exists('galeria/perfil/'.$this->get("usuario").'.jpg')){
			$avatar='galeria/perfil/'.$this->get("usuario").'.jpg';
		}
		else {
			$avatar='galeria/perfil/avatar.png';
		}
		$this->set("avatar",$avatar);
	}
  	return $avatar;
  }
  public function register($datos){
    global $core;
    $db=&$core->getDB();
    $con=&$db->getConexion();
    $q="insert into `usuarios`(`usuario`,`clave`,`nombre_pant`,`stayInTouchCheckbox`,`sendProEmailCheckbox`,`fb_token`,`fb_expire`)
	values(
	  '".mysql_real_escape_string($datos["emailAddr"])."',
	  '".mysql_real_escape_string($datos["password"])."',
	  '".mysql_real_escape_string($datos["screenName"])."',
	  '".($datos["stayInTouchCheckbox"]?"1":"0")."',
	  '".($datos["proCheckbox"]?"1":"0")."',
	  '".mysql_real_escape_string($datos["fbtoken"])."',
	  '".(time()+6000)."')";
    $r=mysql_query($q,$con);
    $this->id=mysql_insert_id($con);
    if($this->id){

	$_SESSION['user_id'] =$this->id;
      $this->logged=true;
	  $actividades=$core->getApp("actividades");
	  $actividades->report($this,'$$has_register$$',$this->getLink());

    $q="insert into `bounds_stock` (`user`,`bound`,`cantidad`,`expire`)
	values(
	  '".mysql_real_escape_string($this->id)."',
	  '1',
	  '1',
	  now()+ INTERVAL 1 year)";
    mysql_query($q);
    }
    else {
      $q="select `u`.`id_cliente` from `usuarios` as `u` where `u`.`usuario`='".mysql_real_escape_string($datos["emailAddr"])."'";
      $r=mysql_query($q,$con);
      if($r&&mysql_num_rows($r)){
	$core->addAlert('$$User_already_exists$$');
      }
      else {
	$core->addAlert('$$User_unknow_error$$');
      }
    }
  }
  public function getLink(){
  	return "/app/user/".$this->id."/".urlencode(str_replace(" ","_",$this->get("nombre_pant")));
  }
  public function login($user="",$pass=""){
    global $core;
      if (!isset($_SESSION)) {
	session_start();
      }
    $db=&$core->getDB();
    $con=&$db->getConexion();
    $q="SELECT id_cliente,usuario, clave, nombre_pant
      FROM usuarios
      WHERE usuario='".mysql_real_escape_string($user)."' and clave = '".mysql_real_escape_string($pass)."'
      limit 1";
    $r=mysql_query($q);
    if(mysql_num_rows($r)){
      $i=mysql_fetch_array($r,MYSQL_ASSOC);
      $_SESSION['MM_Username'] = $i["usuario"];
	$_SESSION['MM_nombre_pant'] = $i["nombre_pant"];
	$_SESSION['user_id'] = $i["id_cliente"];
      $this->logged=true;
      $this->id=$i["id_cliente"];
	  //$actividades=$core->getApp("actividades");
	  //$actividades->report($this,'$$has_login$$',$this->getLink());
      if($_POST["fbtoken"]){
	  $this->set("fb_token",$_POST["fbtoken"]);
	  $this->set("fb_expire",time()+6000);
	}
      }
  }
  public function loginFacebook($code){
    global $core;
      if (!isset($_SESSION)) {
	session_start();
      }
    $db=&$core->getDB();
    $con=&$db->getConexion();
	$facebook=&$core->getApp("facebook");
	
    $q="select `u`.`id_cliente`, `u`.`nombre_pant`
      from `usuarios` as `u`
      where `u`.`fb_id`='".mysql_real_escape_string($code["user_id"])."'
      limit 1";
    $r=mysql_query($q);
    if(mysql_num_rows($r)){
      $i=mysql_fetch_array($r,MYSQL_ASSOC);
      $this->id=$i["id_cliente"];
	  $userdata=$facebook->getData($code["oauth_token"]);
	  $q="update `usuarios` 
	  	set `nombre_pant`='".mysql_real_escape_string($userdata->name)."',
	  	`fb_token`='".mysql_real_escape_string($code["oauth_token"])."',
	  	`fb_expire`='".mysql_real_escape_string($code["expires"])."',
	  	`email`='".mysql_real_escape_string($userdata->email)."'
	  	where
	  		`fb_id`='".mysql_real_escape_string($code["user_id"])."'
	  	limit 1";
	  mysql_query($q);
	    if($this->id){
	    	$this->forceLogin();
      		return true;
		}
      }
	else {
		$userdata=$facebook->getData($code["oauth_token"]);
		$q="insert into `usuarios`(`nombre_pant`,`fb_token`,`fb_id`,`fb_expire`,`email`) values (
			'".mysql_real_escape_string($userdata->name)."',
			'".mysql_real_escape_string($code["oauth_token"])."',
			'".mysql_real_escape_string($code["user_id"])."',
			'".mysql_real_escape_string($code["expires"])."',
			'".mysql_real_escape_string($userdata->email)."'
			)";
		$r=mysql_query($q);
	    $this->id=mysql_insert_id();
	    if($this->id){
	    	$this->forceLogin();
      return true;
		}
	}
    return false;
  }
  public function submitToken($code){
    if($this->logged){
      $this->set("fb_token",$code["access_token"]);
      $this->set("fb_expire",time()+$code["expires"]);
    }
  }
 public function getFavoritos(){
 	$q="select `id_clientefavo`,`id_expedientefavo` from `favoritos` where `id_cliente`='".mysql_real_escape_string($this->id)."'";
	$r=mysql_query($q);
	$res=array();
	while($i = mysql_fetch_array($r,MYSQL_ASSOC)){
		$res[]=new inmueble($i["id_expedientefavo"],$i["id_clientefavo"]);
	}
	return $res;
 }
  public function countFavoritos(){
  	$q="select count(`id_cliente`) as 'total' from `favoritos` where `id_cliente`='".mysql_real_escape_string($this->id)."' group by `id_cliente`";
	$r=mysql_query($q);
	$i=mysql_fetch_array($r,MYSQL_ASSOC);
	return intval($i["total"]);
  }
  public function countAnuncios(){
  	global $core,$user;
	$search=&$core->getApp("search");
  	$inmuebles=$search->searchByUser($this,($user->id==$this->id));
	return count($inmuebles);
  }
  public function countUnreadMessages(){
  	$q="select count(`id_cliente`) as 'total' from `buzon` where `id_cliente`='".mysql_real_escape_string($this->id)."' and `leido`='0'  group by `id_cliente`";
	$r=mysql_query($q);
	$i=mysql_fetch_array($r,MYSQL_ASSOC);
	return intval($i["total"]);
  }
  public function getFreemiumAvaliable(){
  	return $this->getAvaliables(1);
  }
  public function getStandarAvaliable(){
  	return $this->getAvaliables(2);
  }
  public function getBoundAvaliable(){
  	return $this->getAvaliables(3)+$this->getAvaliables(4);
  }
  public function getAvaliables($tip){
  	$q="select (`disponibles`.`total` - `usados`.`total` ) as 'disponibles'
			from
			(select sum(`contratados`.`total`) as 'total'
			 from (
			  select `b`.`id` as 'bound', (`b`.`cantidad`*`bs`.`cantidad`) as 'total'
			    from `bounds_stock` as `bs`
			      left join `bounds` as `b`
			         on `bs`.`bound`=`b`.`id`
			     where 
			      `b`.`id`='".mysql_real_escape_string($tip)."'
			     and `bs`.`user`='".mysql_real_escape_string($this->id)."'
			     and `bs`.`expire`>=now()
			  ) as `contratados`
			group by `contratados`.`bound`) as `disponibles`,
			(select count(`bsi`.`bound`) as 'total' 
			from `bounds_user_inmueble` as `bsi`  
			left join `inmuebles` as `i`
			 on `i`.`id_expediente`=`bsi`.`inmueble`
			where `bsi`.`bound`='".mysql_real_escape_string($tip)."' and `bsi`.`user`='".mysql_real_escape_string($this->id)."'
			and  `i`.`id_expediente`=`bsi`.`inmueble`
			and  `i`.`id_cliente`=`bsi`.`user`
			and `i`.`fecvennormal`>=now()
			
			 ) as `usados`";
	$r=mysql_query($q);
	$i=mysql_fetch_array($r,MYSQL_ASSOC);
  	return $i["disponibles"];
  }
  public function sendPasswordtoEmail(){
  	global $core;
			$mailer=$core->getApp("mailer");
			$mailer->send(array(
				"destinatario"=>$this->get("usuario"),
				"asunto"=>'[[e-spacios.com]]$$password_retrieve$$',
				"plantilla"=>"html/password_retrieve.html",
				"variables"=>array(
					"NOMBRE"=>$this->get("nombre_pant"),
					"PASSWORD"=>$this->get("clave")
					)
				));
  }
}